<template >
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <!-- 点击首页会跳转到home -->
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区 -->
    <el-card border>
      <el-row>
        <el-button type="primary" @click="addRolesShow">添加角色</el-button>
      </el-row>

      <el-table :data="rolesList" border>
        <el-table-column type="expand">
          <template v-slot="scope">
            <el-row
              :class="['bdbottom',i1===0?'bdtop':'','center']"
              v-for=" (item1,i1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 第一层占5列 -->
              <el-col :span="5">
                <el-tag closable @close="deleteTag(scope.row,item1.id)">{{item1.authName}}</el-tag>
              </el-col>
              <!-- 第二层和第三层占19列 -->
              <el-col :span="19">
                <el-row
                  :class="[i2===0?'':'bdtop','center']"
                  v-for="(item2,i2) in item1.children"
                  :key="item2.id"
                >
                  <!-- 第二层占6列 -->
                  <el-col :span="6">
                    <el-tag closable @close="deleteTag(scope.row,item1.id)">{{item2.authName}}</el-tag>
                  </el-col>
                  <!-- 第三层占18列 -->
                  <el-col :span="18">
                    <el-tag
                      closable
                      @close="deleteTag(scope.row,item1.id)"
                      v-for="(item3,i3) in item2.children"
                      :key="item3.id"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <!-- 放入标签中 美化-->
            <!-- <pre>{{scope.row}}</pre> -->
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作">
          <template v-slot="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="editRolesShow(scope.row.id)"
            >编辑</el-button>
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="deleteRoles(scope.row.id)"
            >删除</el-button>
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-setting"
              @click="addRights(scope.row)"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 添加角色 -->
      <el-dialog
        title="添加角色"
        :visible.sync="addRolesVisible"
        width="50%"
        @close="resetAddRolesForm"
      >
        <el-form :model="addRolesForm" :rules="addRolesRules" ref="addRolesRef" label-width="100px">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="addRolesForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="addRolesForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addRolesVisible=false">取 消</el-button>
          <el-button type="primary" @click="addRoles ">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 编辑角色 -->
      <el-dialog
        title="编辑角色"
        :visible.sync="editRolesVisible"
        width="50%"
        @close="resetEditRolesForm"
      >
        <el-form
          :model="editRolesForm"
          :rules="editRolesRules"
          ref="editRolesRef"
          label-width="100px"
        >
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="editRolesForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="editRolesForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editRolesVisible=false">取 消</el-button>
          <el-button type="primary" @click="editRoles ">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 分配权限 -->
      <el-dialog
        title="分配权限"
        :visible.sync="dialogVisibleAddRights"
        width="30%"
        @close="resetSelected"
      >
        <el-tree
          :data="getRightsList"
          :props="defaultProps"
          show-checkbox
          node-key="id"
          default-expand-all
          :default-checked-keys="selected"
          ref="treeRef"
        ></el-tree>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisibleAddRights=false">取 消</el-button>
          <el-button type="primary" @click="addSelectRights">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>




<script>
export default {
  data() {
    return {
      rolesList: [],
      //初始权限数据为空
      getRightsList: [],
      //保存角色的ID，主要供后续addSelectRights（）使用
      roleId: "",
      //树形表
      defaultProps: {
        children: "children",
        label: "authName"
      },
      //默认已有权限勾选
      selected: [],
      addRolesVisible: false,
      editRolesVisible: false,
      dialogVisibleAddRights: false,
      addRolesForm: {
        roleName: "",
        roleDesc: ""
      },
      //表单是对象！！！！！！！！！！
      editRolesForm: {},
      addRolesRules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          { min: 2, max: 5, message: "长度在 2 到 5 个字符", trigger: "blur" }
        ]
      },
      editRolesRules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          { min: 2, max: 5, message: "长度在 2 到 5 个字符", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getRolesList();
  },
  methods: {
    //获取角色列表
    async getRolesList() {
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200) {
        return this.$message.error("获取角色列表失败");
      } else {
        this.rolesList = res.data;
      }
    },
    //显示添加角色Dialog窗口
    addRolesShow() {
      this.addRolesVisible = true;
    },
    //显示编辑角色Dialog窗口
    async editRolesShow(id) {
      this.editRolesVisible = true;
      const { data: res } = await this.$http.get("roles/" + id);
      if (res.meta.status !== 200) {
        return this.$message.error("编辑角色失败");
      } else {
        this.editRolesForm = res.data;
      }
    },
    //进行预验证后添加角色
    addRoles() {
      this.$refs.addRolesRef.validate(async valid => {
        if (!valid) {
          return;
        } else {
          const { data: res } = await this.$http.post(
            "roles/",
            this.addRolesForm
          );
          if (res.meta.status !== 201) {
            return this.$message.error("创建失败");
          } else {
            this.addRolesVisible = false;
            this.$message.success("创建成功");
            this.getRolesList();
          }
        }
      });
    },
    //监听添加角色列表关闭事件
    resetAddRolesForm() {
      this.$refs.addRolesRef.resetFields();
    },
    //进行预验证后编辑角色
    editRoles() {
      this.$refs.editRolesRef.validate(async valid => {
        if (!valid) {
          return;
        } else {
          const { data: res } = await this.$http.put(
            "roles/" + this.editRolesForm.roleId,
            {
              roleName: this.editRolesForm.roleName,
              roleDesc: this.editRolesForm.roleDesc
            }
          );
          if (res.meta.status !== 200) {
            return this.$message.error("编辑失败");
          } else {
            this.editRolesVisible = false;
            this.$message.success("编辑成功");
            this.getRolesList();
          }
        }
      });
    },
    //监听编辑角色列表关闭事件
    resetEditRolesForm() {
      this.$refs.editRolesRef.resetFields();
    },

    //删除角色
    async deleteRoles(id) {
      const result = await this.$confirm(
        "此操作将永久删除该角色, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(error => error);

      if (result !== "confirm") {
        //confirm是字符串！！！而且''号里面不能出现空格！！！！
        return;
      } else {
        const { data: res } = await this.$http.delete("roles/" + id);
        if (res.meta.status !== 200) {
          return;
        } else {
          this.$message.success("删除成功");
          this.getRolesList();
        }
      }
    },
    //删除tag
    async deleteTag(role, rightsId) {
      const result = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);

      if (result !== "confirm") {
        return;
      } else {
        const { data: res } = await this.$http.delete(
          `roles/${role.id}/rights/${rightsId}`
        );
        if (res.meta.status !== 200) {
          return;
        } else {
          this.$message.success("删除权限成功");
          //如果用this.getRolesList()会刷新页面,下面则不会重新刷新页面
          role.children = res.data;
        }
      }
    },
    //分配权限
    async addRights(role) {
      //获取所有权限的数据
      //在添加选中的权限前提前获取角色的ID并保存到data中的roleId中，供后续addSelectRights（）使用
      this.roleId = role.id;
      const { data: res } = await this.$http.get("rights/tree");
      if (res.meta.status !== 200) {
        return;
      } else {
        this.getRightsList = res.data;
        this.getKeys(role, this.selected);
        this.dialogVisibleAddRights = true;
      }
    },
    //遍历得到三级节点：如果不包含children属性，为三级节点
    getKeys(node, arr) {
      if (!node.children) {
        return arr.push(node.id); //这里错的原因是写了arr应该是node.id
      } else {
        node.children.forEach(item => {
          //这里错的原因是遍历node里的children而不是遍历arr
          this.getKeys(item, arr);
        });
      }
    },
    //关闭分配权限对话框后，重置selected数组以免出现bug
    resetSelected() {
      this.selected = [];
    },
    //添加选中的权限
    async addSelectRights() {
      const arr = [
        //getCheckedKeys和getHalfCheckedKeys是一个方法，（）别忘记了
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ];
      const str = arr.join(",");
      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        {
          rids: str
        }
      );
      if (res.meta.status !== 200) {
        return this.$message.error("添加失败");
      } else {
        this.$message.success("添加成功");
        this.getRolesList();
        this.dialogVisibleAddRights = false;
      }
    }
  }
};
</script>
<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.center {
  //在class里面的数组要加''号
  display: flex;
  align-items: center;
}
</style>